/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.databox.xmlinterceptor;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import twaver.DataBoxOutputSetting;
import twaver.Element;
import twaver.Node;
import twaver.TDataBox;
import twaver.TWaverConst;
import twaver.TWaverUtil;
import twaver.XMLInterceptor;

public class XMLInterceptorDemo {

	public static void main(String[] args) {
		TWaverUtil.setXMLInterceptor(new XMLInterceptor(){
			public InputStream beforeRead(TDataBox box, InputStream in, Element parentOfRootElement) {
				System.out.println("before Read");
				byte[] data = TWaverUtil.getByteArrayFromInputStream(in);
				try {
					String xml = new String(data, TWaverConst.DEFAULT_ENCODING);
					String version = TWaverUtil.getDataBoxVersion(xml);
					if("version 2.0".equals(version)){
						xml = xml.replaceAll("twaver.Node", "twaver.SubNetwork");
						return new ByteArrayInputStream(xml.getBytes(TWaverConst.DEFAULT_ENCODING));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return new ByteArrayInputStream(data);
			}
			public void afterRead(TDataBox box, InputStream in, Element parentOfRootElement) {
				System.out.println("after Read");
				box.setVersion("version 3.0");
			}
			public void beforeWrite(TDataBox box, DataBoxOutputSetting setting) {
				System.out.println("before Write");
			}
			public void afterWrite(TDataBox box, DataBoxOutputSetting setting) {
				System.out.println("after Write");
			}
		});
		
		TDataBox box = new TDataBox();
		Node node = new Node();
		node.setName("I am elmenet");
		box.addElement(node);
		box.setVersion("version 2.0");
		String xml = box.toXML();
		
		box = new TDataBox();
		box.parseXML(xml);
		System.out.println(box.toXML());

	}

}